import Vue from 'vue'
import * as Constant from './constant'
// import store from '../store'
import { ALERT } from './responseHandle'

let vinstance = new Vue()

let currentRef = null

let commonUtil = {
  /**
   * @param {*} model 域对象
   * {
   *   content：提示的内容,(默认'是否删除，请确认！')
   *   type:icon类型,(默认'warning')
   *   successMsg:确定后的提示信息,(默认'删除成功')
   *   cancelFunc: 取消后的提示信息,(默认'已取消删除')
   *   autoMessage: 是否使用确定后的前端提示信息（默认 'false'）
   * }
   * @param {*} confirmFunc 确定的回调
   * @param {*} cancelFunc 取消的回调
   */
  confirm: function (model, confirmFunc, cancelFunc) {
    // return vinstance.$confirm(msg).catch(_ => { })
    const { content = '是否删除，请确认！', type = 'warning', successMsg = '删除成功', cancelMsg = '已取消删除', autoMessage = false } = model
    vinstance.$confirm(content, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: type
    }).then(() => {
      if (typeof (confirmFunc) === 'function') {
        confirmFunc()
      }
      if (autoMessage) {
        vinstance.$message({
          type: 'success',
          message: successMsg
        })
      }
    }).catch(() => {
      if (typeof (cancelFunc) === 'function') {
        cancelFunc()
      }
      vinstance.$message({
        type: 'info',
        message: cancelMsg
      })
    })
  },
  clearData: function (data) {
    for (var d in data) {
      data[d] = null
    }
  },
  copy: function (sources, target) {
    // for (var key in sources) {
    //   if (sources.hasOwnProperty(key)) {
    //     target[key] = sources[key]
    //   }
    // }
    return Object.assign(target, sources)
  },
  clone: function (data) {
    return Object.assign({}, data)
  },
  deepClone: function (obj) {
    if (!obj || typeof obj !== 'object') {
      return
    }
    var dcObj = Array.isArray(obj) ? [] : {}
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          dcObj[key] = Array.isArray(obj[key]) ? [] : {}
          dcObj[key] = this.deepCopy(obj[key])
        }
        dcObj[key] = obj[key]
      }
    }
    return dcObj
  },
  httpCallBack_OK: function (callback, response, finnly) {
    if (response.status === Constant.RESP_STATE_SUCCESS) {
      callback(response)
    } else {
      ALERT.errorDefault(response)
    }
    if (finnly) {
      finnly(response)
    }
  },
  showHttpError: function () {
    ALERT.error('调用接口失败！')
  },
  showLoading: function (msg) {
    this.loading = vinstance.$loading({
      lock: true,
      text: msg !== undefined ? msg : '',
      spinner: 'el-icon-loading',
      background: 'rgba(238, 238, 238, 0.5)'
    })
  },
  hideLoading: function () {
    this.loading && this.loading.close()
  },
  routerTo: function (path, rt, params) {
    if (rt.history.current.path === path) {
      rt.push(Constant.ROUTE_EMPTY.index)
      setTimeout(function () {
        if (params) {
          rt.push({ name: path, params: params })
        } else {
          rt.push(path)
        }
      }, 50)
      return
    }
    // vinstance.$router.push('/' + store.state.account.auth.client_id + path)
    // this.$router.push({name: 'catalogueAdd', params: {id: 123}})
    if (params) {
      rt.push({ name: path, params: params })
      // rt.push('/' + store.state.account.auth.client_id + '/' + path + '/12323')
    } else {
      rt.push(path)
    }
  },
  createDownloadLink: function (data, filename) {
    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/octet-stream;charset=utf-8' }))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href) // 释放URL 对象
    document.body.removeChild(link)
  },
  downloadLinkByUrl: function (url, filename) {
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)
    console.log("--143-commonutil.js-",filename);
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href) // 释放URL 对象
    document.body.removeChild(link)
    console.log("--148-commonutil.js-",link.href);
  },
  setCurrentRef: function (ref) {
    currentRef = ref
  },
  getCurrentRef: function (ref) {
    return currentRef
  },
  isNullOrUndefined: function (val) {
    return val === null || val === undefined
  },
  isNullOrUndefinedOrSpace: function (val) {
    return val === null || val === undefined || /^\s*$/.test(val)
  },
  isNullOrSpace: function (val) {
    return val === null || val === undefined || /^\s*$/.test(val)
  },
  isInteger (val) {
    return val !== null && val !== undefined && typeof val === 'number'
  },
  joinValuesToString (...vals) {
    if (this.isNullOrUndefined(vals) || vals.length === 0) {
      return ''
    } else {
      return vals.map(item => {
        return this.isNullOrUndefined(item) ? '' : item
      }).join('')
    }
  },
  /**
   * 校验时间字符串格式为：yyyy-MM-dd HH:mm:ss
   * @param {*} strTime 字符串时间
   */
  isDateYyyyMMddHHmmss (strTime) {
    return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(strTime)
  },

  /**
   * 数组转成字符串
   * @param {*} list 转换的数组
   * @param {*} key 需要转换为字符串的key
   */
  arrToStr (list,key) {
    let str = ""
    if(Array.isArray(list)&&list.length>0){
      str = list.map(item=>key?item.peopleName:item).join(",")
    }
    return str;
  },
 /**
   * 转化人员选择数据
   * @param {*} ref ref
   * @param {*} multiple 多选还是单选
   */
  changePersonSelectData(ref,multiple=true){
    let val = ref.currentValue;
    if(multiple){
      let arr = val.split(",");
      return arr.map(item=>{
        return{
          peopleNumber:item.substr(1,item.indexOf(']')-1),
          peopleName:item,//item.substr(item.indexOf(']')+1)
        }
      })
    }else{
      return {
        peopleNumber:val.substr(1,val.indexOf(']')-1),
        peopleName:val,//val.substr(val.indexOf(']')+1)
      }
    }

  },
  /**
   * 验证url
   * @param {*} URL
   */
  checkURL (URL) {
    var str = URL,
    // Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,
    Expression = /http(s)?:\/\/?/,
    objExp = new RegExp(Expression)
    if(objExp.test(str) == true) {
       return true
    } else {
       return false
    }
  },
  //限制输入框数值为保留count位小数点
  limitInputCount(object,key,count=2){
        object[key] = object[key]
                .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
                .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
                .replace('.', '$#$')
                .replace(/\./g, '')
                .replace('$#$', '.')
                .replace(new RegExp("^(\\-)*(\\d+)\\.(\\d{" + count + "}).*$"), '$1$2.$3'); // 只能输入count个小数
            if (object[key].indexOf('.') < 0 && object[key] != '') {
                // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
                object[key] = parseFloat(object[key]);
            }
    },

    //限制输入框数值为正整数
    limitPositiveInteger(object,key){
        object[key] = object[key].replace(/[^\d]/g, '') // 清除“数字”以外的字符
    },

  /**
   * 防抖
   * @param fnName 需要防抖的函数
   * @param delay 延时时间，单位毫秒
   * @param fnParams fn函数携带的其他参数
   */
  debounce(fnName, delay=500,fnParams) {
    let timeout = null;
    return function() {
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        this[fnName](fnParams);
      }, delay);
    };
  }
}

function initIns () {
  return commonUtil
}

export const COMMON = initIns()
